﻿window.Q = null;
window.Connected = false;

_Send = function (data) {
	if (Q && Q.readyState === Q.OPEN)
		Q.send(JSON.stringify(data));
	else
		console.log("Attempt to send while WebSocket is not ready", data);
};
window.CMD = {
	Join: function (channel, nick, callback) {
		window._JoinCallback = callback;
		_Send({
			cmd: 'join',
			channel: channel,
			nick: nick
		});
	},
	Chat: function (text) {
		_Send({
			cmd: 'chat',
			text: text
		});
	}
};

function atBottom() {
	return (window.innerHeight + window.scrollY) >= (document.body.scrollHeight - 1);
}

function toBottom() {
	window.scrollTo(0, document.body.scrollHeight);
}

function appendMsg(name, content, color) {
	if (!color) color = "white";
	var div = $("<div></div>");
	div.addClass("Message");
	div.append($("<p></p>").text(name).addClass("Name").css({"color": color}));
	div.append($("<p></p>").text(content).addClass("Content").css({"color": color}));
	var at = atBottom();
	_Chats.append(div);
	if (at) toBottom();
}

//Synchornized
var _MarkdownToHtml = false;

function MarkdownToHtml(obj, md) {
	while (_MarkdownToHtml) ;
	obj.append($('<textarea id="MarkdownTemp" style="display:none;"></textarea>').val(md));
	obj.attr("id", "MarkdownResult");
	_MarkdownToHtml = true;
	res = editormd.markdownToHTML("MarkdownResult", {
		htmlDecode: "style,script,iframe",
		emoji: true,
		taskList: true,
		tex: true,
		flowChart: true,
		sequenceDiagram: true
	});
	obj.css({"padding": "0 0 0 1em"});
	obj.attr("id", null);
	_MarkdownToHtml = false;
}

function systemInfo(content) {
	appendMsg("系统信息", content, "green");
}

function onRecvMsg(msg) {
	switch (msg.cmd) {
		case "onlineSet": {
			if (window._JoinCallback) {
				window._JoinCallback();
				delete window._JoinCallback;
			}
			systemInfo((function () {
				var s = "目前在线用户：";
				for (var i = 0; i < msg.nicks.length; i++) {
					if (i !== 0) s += ", ";
					s += msg.nicks[i];
				}
				return s;
			})());
			break;
		}
		case "onlineRemove": {
			systemInfo("用户 " + msg.nick + " 离开了房间");
			break;
		}
		case "onlineAdd": {
			systemInfo("用户 " + msg.nick + " 加入了房间");
			break;
		}
		case "chat": {
			var at = atBottom();
			console.log(at);
			var div = $("<div></div>");
			div.append($("<p></p>").text(msg.nick).addClass("Name").css({"color": "white"}));
			var content = $("<div></div>");
			div.append(content);
			_Chats.append(div);
			_Chats.append("<hr>");
			MarkdownToHtml(content, msg.text);
			if (at) toBottom();
			break;
		}
		case "warn": {
			if (msg.text === "Nickname taken") {
				$("#InputContainer")
					.css({"display": "initial"})
					.css({"opacity": "1"});
				_NameStatus.text("用户名已被占用");
				setStatus("");
			}
			break;
		}
	}
}

function JoinChannel(channel, nick) {
	setStatus("连接中");
	Q = new WebSocket('wss://hack.chat/chat-ws');
	window.Connected = false;
	Q.onopen = function () {
		window.Connected = true;
		setStatus("加入聊天室中");
		CMD.Join(channel, nick, function () {
			setStatus("成功");
			var LeftCover = $(".LeftCover");
			LeftCover.bind('transitionend', function () {
				LeftCover.remove();
			});
			LeftCover.addClass("LeftCoverHide");
			var RightCover = $(".RightCover");
			RightCover.bind('transitionend', function () {
				RightCover.remove();
			});
			RightCover.addClass("RightCoverHide");
			window._StatusText.bind('transitionend', function () {
				window._StatusText.unbind('transitionend');
				window._StatusText.remove();
				$("#ChatContainer").css({"position": ""});
				$(document.body).css({"overflow-y": "scroll"});
			});
			setTimeout('window._StatusText.css({"opacity": "0"});', 500);
			$("#ChatPanel").css({"margin-bottom": $("#ShowEditor").outerHeight()});
		});
	};
	Q.onmessage = function (msg) {
		var data = JSON.parse(msg.data);
		console.log(data);
		onRecvMsg(data);
	}
}

function setStatus(s) {
	if (window._StatusText)
		window._StatusText.text(s);
}

function PostConnect() {
	var n = _NameInput.val();
	if (n.length === 0) {
		_NameStatus.text("用户名不能为空");
		return;
	}
	if (n.length > 24) {
		_NameStatus.text("用户名不能超过24个字符");
		return;
	}
	if (!(/^[a-zA-Z0-9_]{1,24}$/.test(n))) {
		_NameStatus.text("用户名不合法");
		return;
	}
	var InputContainer = $("#InputContainer");
	InputContainer.bind('transitionend', function () {
		InputContainer.css({"display": "none"});
		InputContainer.unbind('transitionend');
	});
	InputContainer.css({"opacity": "0"});
	JoinChannel("LuoGu_Chat", n);
}

$(window).load(function () {
	window._StatusText = $("#StatusText");
	window._TextContainer = $("#TextContainer");
	window._NameInput = $("#NameInput");
	window._Chats = $("#Chats");
	window._NameStatus = $("#NameStatus");
	window._ChatPanel = $("#ChatPanel");
	window._MarkdownPanel = $("#MarkdownPanel");
	_NameInput.bind('keydown', function (event) {
		if (event.keyCode === 13)
			PostConnect();
	});
	$("#Connect").bind('click', function () {
		PostConnect();
	});
	_NameInput.focus();
	window.Editor = editormd("EditorMdContainer", {
		width: "100vw",
		height: ($("#MarkdownPanel").outerHeight() - $("#ShowEditor").outerHeight()) + "px",
		placeholder: "写点新鲜事",
		path: "EditorMd/lib/",
		htmlDecode: "style,script,iframe",
		emoji: true,
		taskList: true,
		tex: true,
		flowChart: true,
		sequenceDiagram: true
	});
});

var LastScrollHeight = -1;
function ToggleEditor() {
	LastScrollHeight = window.scrollY;
	_ChatPanel.css({"display": "none"});
	_MarkdownPanel.css({"display": ""});
	$(document.body).css({"overflow-y": "hidden"});
	Editor.resize();
	window.scrollTo(0, 0);
}

function ToggleMain() {
	_ChatPanel.css({"display": ""});
	_MarkdownPanel.css({"display": "none"});
	$(document.body).css({"overflow-y": "scroll"});
	if (LastScrollHeight!==-1) {
		window.scrollTo(0, LastScrollHeight);
		LastScrollHeight = -1;
	}
}

function Submit() {
	var content = Editor.getMarkdown();
	if (content.length === 0)
		return;
	CMD.Chat(content);
	Editor.setMarkdown("");
	ToggleMain();
}